#include "TextureCubeMap.h"


bool TextureCubeMap::LoadImage() 
{
	size_t count = paths.size();

	if(count != 6)
	{
		return false;
	}

	ILuint* imageIds = new ILuint[count];
	ilGenImages(count, imageIds); // Generation of numTextures image names 
		
	glGenTextures(1, &textureID);
	Bind();

	for(size_t i = 0; i < count; i++)
	{
		ilBindImage(imageIds[i]); // Binding of DevIL image name 
		ILboolean success = ilLoadImage(paths[i].c_str());
		if(ilGetInteger(IL_IMAGE_FORMAT) == IL_RGB)
		{
			success = ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE);
		}
		else if(ilGetInteger(IL_IMAGE_FORMAT) == IL_RGBA)
		{
			success = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
		}

		if(!success)
		{
			ilBindImage(0);
			ilDeleteImages(count, imageIds); // Because we have already copied image data into texture data we can release memory used by image. 
			return false;
		}

		ILuint width, height;
		width = ilGetInteger(IL_IMAGE_WIDTH);
		height = ilGetInteger(IL_IMAGE_HEIGHT);

		glTexImage2D(faces.at(i), 0, GL_RGB, width, height, 0, ilGetInteger(IL_IMAGE_FORMAT),  GL_UNSIGNED_BYTE, ilGetData());
		glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 
		glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
	}
		
	std::string firstFileName = GetFileName(paths[0]);
	SetPath(paths[0]);
	Texture::textureMap.insert(std::pair<std::string, std::shared_ptr<Texture>>(firstFileName, this));

	Unbind();
		
	//clean up
	ilBindImage(0);
	ilDeleteImages(count, imageIds); 
	return true;
}